package com.winning.shiro.shiroboot.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author chensj
 * @title
 * @email chensj@
 * @package com.winning.shiro.web
 * @date: 2019-01-19 下午9:33
 */
@Controller
@RequestMapping(value = "/shiro")
public class LoginController {

    @RequestMapping(value = "/login")
    public String login(@RequestParam("username") String username,@RequestParam("password") String password){
        Subject currentUser = SecurityUtils.getSubject();
        if(!currentUser.isAuthenticated()){
            //封装用户名密码到UsernamePasswordToke中
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            // 记住我
            token.setRememberMe(true);
            try {
                // 执行登录
                currentUser.login(token);
            }catch (AuthenticationException e){
                System.out.println("登录失败:"+e.getMessage());
                // throw new RuntimeException(e.getMessage());
            }
        }
        return "redirect:/main.jsp";
    }
}
